import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  DatePicker,
  Space,
  Modal,
  message,
  Popconfirm,
  Tooltip,
  Tag,
  Dropdown
} from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  QrcodeOutlined, 
  DownloadOutlined,
  FilterOutlined,
  ReloadOutlined,
  EyeOutlined,
  FileExcelOutlined
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { 
  fetchDevices, 
  deleteDevice, 
  setFilters, 
  setPage, 
  setPageSize,
  setSelectedDevices
} from '../redux/features/deviceSlice';
import DeviceForm from '../components/DeviceForm';
import { formatDate } from '../utils/tools';
import { exportDevicesToExcel, batchDeleteDevices, exportSelectedDevices, validateExportData, formatExportFilename } from '../utils/exportTools';
import './DeviceListPage.css';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Search } = Input;



const DeviceListPage = () => {
  const dispatch = useDispatch();
  const { 
    devices, 
    isLoading, 
    error, 
    total, 
    page, 
    pageSize, 
    filters, 
    selectedDevices 
  } = useSelector((state) => state.device);
  

  
  const [searchText, setSearchText] = useState('');
  const [filterVisible, setFilterVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentDevice, setCurrentDevice] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);

  // 设备类型选项
  const deviceTypes = [
    '服务器', '网络设备', '存储设备', '安全设备',
    '终端设备', '办公设备', '生产设备', '其他设备'
  ];

  // 分页配置
  const pagination = {
    current: page,
    pageSize: pageSize,
    total: total,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条记录`,
    pageSizeOptions: ['10', '20', '50', '100'],
    onChange: (currentPage) => dispatch(setPage(currentPage)),
    onShowSizeChange: (_, newPageSize) => dispatch(setPageSize(newPageSize)),
  };

  // 表格列配置
  const columns = [
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
      sorter: (a, b) => a.deviceName.localeCompare(b.deviceName),
    },
    {
      title: '设备编号',
      dataIndex: 'deviceCode',
      key: 'deviceCode',
      sorter: (a, b) => a.deviceCode.localeCompare(b.deviceCode),
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      filters: deviceTypes.map(type => ({ text: type, value: type })),
      onFilter: (value, record) => record.deviceType === value,
      render: (type) => <Tag color="blue">{type}</Tag>,
    },
    {
      title: '生产日期',
      dataIndex: 'productionDate',
      key: 'productionDate',
      sorter: (a, b) => new Date(a.productionDate) - new Date(b.productionDate),
      render: (date) => formatDate(date),
    },
    {
      title: '是否生成二维码',
      dataIndex: 'qrcodeUrl',
      key: 'has_qrcode',
      render: (url) => url ? <Tag color="success">已生成</Tag> : <Tag color="default">未生成</Tag>,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 180,
      render: (_, record) => (
        <Space size="middle">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              size="small" 
              onClick={() => handleViewDetail(record)} 
            />
          </Tooltip>
          <Tooltip title="编辑设备">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              size="small" 
              onClick={() => handleEdit(record)} 
            />
          </Tooltip>
          <Tooltip title="生成二维码">
            <Button 
              type="text" 
              icon={<QrcodeOutlined />} 
              size="small" 
              onClick={() => handleGenerateQrCode(record.id)} 
            />
          </Tooltip>
          <Tooltip title="删除设备">
            <Popconfirm
              title="确认删除"
              description="确定要删除此设备吗？删除后数据将无法恢复。"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="text" 
                danger 
                icon={<DeleteOutlined />} 
                size="small" 
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 获取设备列表数据
  useEffect(() => {
    const fetchData = async () => {
      console.log('DeviceListPage - 开始获取设备列表数据', {
        filters,
        page,
        pageSize,
        keyword: searchText,
        currentDevicesBeforeFetch: devices,
        currentTotalBeforeFetch: total
      });
      try {
        console.log('DeviceListPage - 即将调用dispatch(fetchDevices)');
        const result = await dispatch(fetchDevices({ ...filters, page, pageSize, keyword: searchText })).unwrap();
        console.log('DeviceListPage - 获取设备列表数据成功', {
          result,
          totalDevices: result?.total || 0,
          fetchedDevicesCount: result?.devices?.length || 0
        });
        console.log('DeviceListPage - fetchData完成后的设备数据:', {
          newDevices: devices,
          newTotal: total
        });
      } catch (error) {
        console.error('DeviceListPage - 获取设备列表数据失败', error);
        message.error('获取设备列表失败');
      }
    }

    console.log('DeviceListPage - useEffect触发，调用fetchData');
    fetchData();
  }, [dispatch, filters, page, pageSize, searchText]);

  // 添加组件挂载时的日志和监控
  useEffect(() => {
    console.log('DeviceListPage - 组件挂载，初始Redux状态:', {
      initialDevices: devices,
      initialTotal: total,
      initialIsLoading: isLoading,
      initialError: error
    });
    // 确保设备列表数据已加载
    if (!isLoading && (!devices || devices.length === 0)) {
      console.log('DeviceListPage - 挂载时检测到设备数据为空，触发获取');
      dispatch(fetchDevices({ ...filters, page: 1, pageSize, keyword: searchText }));
    }
  }, []);
  
  // 监控 devices 状态变化
  useEffect(() => {
    console.log('DeviceListPage - devices 状态已更新:', {
      devices: devices,
      hasDevices: devices && devices.length > 0,
      deviceCount: devices ? devices.length : 0
    });
  }, [devices]);

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
    dispatch(setPage(1)); // 搜索时重置到第一页
  };

  // 处理筛选
  const handleFilter = (values) => {
    dispatch(setFilters(values));
    dispatch(setPage(1)); // 筛选时重置到第一页
    setFilterVisible(false);
  };

  // 处理编辑
  const handleEdit = (device) => {
    setCurrentDevice(device);
    setEditModalVisible(true);
  };

  // 处理删除
  const handleDelete = async (id) => {
    try {
      await dispatch(deleteDevice(id)).unwrap();
      message.success('设备删除成功');
    } catch (error) {
      message.error(error?.message || '设备删除失败');
    }
  };

  // 处理生成二维码
  const handleGenerateQrCode = async (id) => {
    try {
      // 实际项目中应该调用API生成二维码
      message.success('二维码生成成功');
    } catch (error) {
      message.error('二维码生成失败');
    }
  };

  // 处理查看详情
  const handleViewDetail = (device) => {
    setCurrentDevice(device);
    setDetailModalVisible(true);
  };

  // 处理创建设备
  const handleCreate = () => {
    setCurrentDevice(null);
    setEditModalVisible(true);
  };

  // 处理表单成功提交
  const handleFormSuccess = () => {
    setEditModalVisible(false);
    dispatch(fetchDevices({ ...filters, page, pageSize, keyword: searchText }));
  };

  // 刷新设备列表
  const handleRefresh = () => {
    dispatch(fetchDevices({ ...filters, page, pageSize, keyword: searchText }));
  };

  // 批量删除
  const handleBatchDelete = async () => {
    await batchDeleteDevices(selectedDevices, async (id) => {
      return dispatch(deleteDevice(id)).unwrap();
    }, () => {
      dispatch(setSelectedDevices([]));
      dispatch(fetchDevices({ ...filters, page, pageSize, keyword: searchText }));
    });
  };

  // 导出所有设备
  const handleExportAll = () => {
    if (validateExportData(devices)) {
      const filename = formatExportFilename('设备列表');
      exportDevicesToExcel(devices, filename);
    }
  };

  // 导出选中设备
  const handleExportSelected = () => {
    exportSelectedDevices(selectedDevices, devices, exportDevicesToExcel);
  };

  // 在表格渲染前打印当前使用的表格数据
  console.log('DeviceListPage - 表格即将渲染，当前使用的数据:', {
    dataSource: devices || [],
    dataCount: devices?.length || 0,
    hasData: devices && devices.length > 0,
    total: total,
    isLoading: isLoading,
    error: error
  });
  
  // 打印详细的设备数据结构
  console.log('DeviceListPage - 完整设备数据:', JSON.stringify(devices, null, 2));
  
  // 添加额外的调试信息
  console.log('DeviceListPage - Redux store 状态:', {
    deviceState: { devices, isLoading, error, total, page, pageSize, filters, selectedDevices }
  });
  
  // 打印表格数据的前5条示例
  if (devices && devices.length > 0) {
    console.log('DeviceListPage - 表格数据前5条示例:', devices.slice(0, 5).map(device => ({
      id: device.id,
      deviceName: device.deviceName,
      deviceCode: device.deviceCode,
      deviceType: device.deviceType,
      hasQrcode: !!device.qrcodeUrl
    })));
  } else if (!isLoading) {
    console.log('DeviceListPage - 暂无设备数据');
  }
  
  return (
    <div className="device-list-container">
      <div className="device-list-header">
        <div className="header-left">
          <h2 className="page-title">设备管理</h2>
        </div>
        <div className="header-right">
          <Space size="middle">
            <Button 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh} 
              loading={isLoading}
              title="刷新列表"
            >
              刷新
            </Button>
            {selectedDevices.length > 0 && (
              <Popconfirm
                title="批量删除"
                description={`确定要删除选中的 ${selectedDevices.length} 个设备吗？删除后数据将无法恢复。`}
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button danger icon={<DeleteOutlined />}>
                  批量删除
                </Button>
              </Popconfirm>
            )}
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={handleCreate}
            >
              创建设备
            </Button>
          </Space>
        </div>
      </div>

      <div className="device-list-toolbar">
        <Space size="middle" wrap>
          <Search
            placeholder="搜索设备名称/编号"
            onSearch={handleSearch}
            style={{ width: 300 }}
            enterButton
            allowClear
          />
          <Button 
            icon={<FilterOutlined />} 
            onClick={() => setFilterVisible(true)}
          >
            高级筛选
          </Button>
          <Dropdown 
            menu={{ 
              items: [
                {
                  key: '1',
                  label: (
                    <Button 
                      type="link" 
                      icon={<FileExcelOutlined />} 
                      size="small" 
                      onClick={handleExportAll}
                    >
                      导出所有设备
                    </Button>
                  ),
                },
                {
                  key: '2',
                  label: (
                    <Button 
                      type="link" 
                      icon={<FileExcelOutlined />} 
                      size="small" 
                      onClick={handleExportSelected}
                      disabled={selectedDevices.length === 0}
                    >
                      导出选中设备
                    </Button>
                  ),
                },
              ],
            }}
            trigger={['click']}
          >
            <Button icon={<DownloadOutlined />}>
              导出数据
            </Button>
          </Dropdown>
        </Space>
      </div>

      <div className="device-list-content">
        <Table
          columns={columns}
          dataSource={devices || []} // 使用从Redux获取的devices数据
          rowKey="id"
          loading={isLoading}
          pagination={pagination}
          rowSelection={{
            onChange: (selectedRowKeys) => dispatch(setSelectedDevices(selectedRowKeys)),
            selectedRowKeys: selectedDevices,
          }}
          scroll={{ x: 1000 }}
          size="middle"
          className="device-table"
        />
      </div>

      {/* 编辑/创建模态框 */}
      <Modal
        title={currentDevice ? "编辑设备" : "创建设备"}
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={700}
      >
        <DeviceForm 
          device={currentDevice} 
          onSuccess={handleFormSuccess}
          onCancel={() => setEditModalVisible(false)}
        />
      </Modal>

      {/* 详情模态框 */}
      <Modal
        title="设备详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={700}
      >
        {currentDevice && (
          <div className="device-detail">
            <div className="detail-row">
              <div className="detail-label">设备名称：</div>
              <div className="detail-value">{currentDevice.deviceName}</div>
            </div>
            <div className="detail-row">
              <div className="detail-label">设备编号：</div>
              <div className="detail-value">{currentDevice.deviceCode}</div>
            </div>
            <div className="detail-row">
              <div className="detail-label">设备类型：</div>
              <div className="detail-value">{currentDevice.deviceType}</div>
            </div>
            <div className="detail-row">
              <div className="detail-label">生产日期：</div>
              <div className="detail-value">{formatDate(currentDevice.productionDate)}</div>
            </div>
            <div className="detail-row">
              <div className="detail-label">设备描述：</div>
              <div className="detail-value">{currentDevice.description || '无'}</div>
            </div>
            <div className="detail-row">
              <div className="detail-label">创建时间：</div>
              <div className="detail-value">{formatDate(currentDevice.createdAt, 'YYYY-MM-DD HH:mm:ss')}</div>
            </div>
            <div className="detail-row">
              <div className="detail-label">更新时间：</div>
              <div className="detail-value">{formatDate(currentDevice.updatedAt, 'YYYY-MM-DD HH:mm:ss')}</div>
            </div>
          </div>
        )}
      </Modal>

      {/* 高级筛选模态框 */}
      <Modal
        title="高级筛选"
        open={filterVisible}
        onCancel={() => setFilterVisible(false)}
        footer={[
          <Button key="reset" onClick={() => handleFilter({})}>
            重置
          </Button>,
          <Button key="cancel" onClick={() => setFilterVisible(false)}>
            取消
          </Button>,
          <Button key="confirm" type="primary" onClick={() => handleFilter(filters)}>
            确定
          </Button>
        ]}
        width={600}
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          <div className="filter-item">
            <div className="filter-label">设备类型：</div>
            <Select
              style={{ width: '100%' }}
              placeholder="请选择设备类型"
              value={filters.device_type}
              onChange={(value) => dispatch(setFilters({ device_type: value }))}
              allowClear
            >
              {deviceTypes.map((type) => (
                <Option key={type} value={type}>{type}</Option>
              ))}
            </Select>
          </div>
          <div className="filter-item">
            <div className="filter-label">生产日期范围：</div>
            <RangePicker
              style={{ width: '100%' }}
              value={filters.date_range ? [
                filters.date_range[0] ? new Date(filters.date_range[0]) : null,
                filters.date_range[1] ? new Date(filters.date_range[1]) : null
              ] : null}
              onChange={(dates) => {
                if (dates) {
                  dispatch(setFilters({
                    date_range: [
                      dates[0] ? dates[0].format('YYYY-MM-DD') : null,
                      dates[1] ? dates[1].format('YYYY-MM-DD') : null
                    ]
                  }));
                } else {
                  dispatch(setFilters({ date_range: null }));
                }
              }}
            />
          </div>
        </Space>
      </Modal>

      {error && (
        <div className="error-message">
          {typeof error === 'string' ? error : error.message || '发生错误，请稍后再试'}
        </div>
      )}
    </div>
  );
};

export default DeviceListPage;